package com.baidu.st.fe.spllot.load;

import java.io.LineNumberReader;
import java.io.Reader;
import java.lang.ref.SoftReference;
import java.util.LinkedHashMap;
import java.util.Map;

public abstract class CodeLoader {
	private SoftReference<Map<Integer, String>> code;

	protected abstract Reader getReader() throws Exception;

	public Map<Integer, String> getCode() {
		Map<Integer, String> cs = null;
		if (code != null) {
			cs = code.get();
		}
		if (cs != null) {
			return cs;
		}
		this.code = new SoftReference<Map<Integer, String>>(load());
		return code.get();
	}

	protected Map<Integer, String> load() {
		LineNumberReader lnr = null;
		try {
			lnr = new LineNumberReader(getReader());
			Map<Integer, String> lines = new LinkedHashMap<Integer, String>();
			String currentLine = "";
			int lineNum = 1;
			while ((currentLine = lnr.readLine()) != null) {
				lines.put(lineNum++, currentLine);
			}
			return lines;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			throw new RuntimeException("Problem when reading file...");
		} finally {
			try {
				if (lnr != null) {
					lnr.close();
				}
			} catch (Exception e) {
				// TODO: handle exception
				throw new RuntimeException("Problem when reading file...");
			}
		}
	}
}
